import axios, { AxiosRequestConfig } from 'axios';
import proxy from '../configs/host';
import { store } from '../modules/store';

const env = 'development';
const API_HOST = proxy[env].API;

const SUCCESS_CODE = 200;
const TIMEOUT = 5000;
export interface IResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

export const instance = axios.create({
  baseURL: API_HOST,
  timeout: TIMEOUT,
  withCredentials: true,
});

instance.interceptors.request.use((request) => {
  const { token } = store.getState().user;
  /**
   * 全局拦截请求发送前提交的参数
   * 以下代码为示例，在请求头里带上 token 信息
   */
  if (token) {
    console.log(`已登录 ${token}`);
    request.headers.token = token;
  }
  return request;
});
instance.interceptors.response.use(
  // eslint-disable-next-line consistent-return
  (response) => {
    if (response.status === 200) {
      const { data } = response;
      if (data.code === SUCCESS_CODE) {
        return data;
      }
      return data;
    }
    return Promise.reject(response?.data);
  },
  (e) => Promise.reject(e),
);

export const request = async <T = any>(config: AxiosRequestConfig): Promise<IResponse<T>> => instance.request(config);

export default instance;
